package main

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
)

type Login struct {
	User     string `form:"user" json:"user" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
}

var login Login

func jsonHandler(c *gin.Context) {
	// ShouldBind()会根据请求的Content-Type自行选择绑定器
	if err := c.ShouldBind(&login); err == nil {
		fmt.Printf("%#v\n", login)
		c.JSON(http.StatusOK, gin.H{
			"user":     login.User,
			"password": login.Password,
		})
	} else {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	}
}
func formHandler(c *gin.Context) {
	// ShouldBind()会根据请求的Content-Type自行选择绑定器
	if err := c.ShouldBind(&login); err == nil {
		c.JSON(http.StatusOK, gin.H{
			"user":     login.User,
			"password": login.Password,
		})
	} else {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	}
}
func querystringHandler(c *gin.Context) {
	// ShouldBind()会根据请求的Content-Type自行选择绑定器
	if err := c.ShouldBind(&login); err == nil {
		c.JSON(http.StatusOK, gin.H{
			"user":     login.User,
			"password": login.Password,
		})
	} else {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	}
}

func main() {
	// 启动默认驱动
	r := gin.Default()
	//绑定json
	r.POST("/loginJson", jsonHandler)
	//绑定form表单
	r.POST("/loginForm", formHandler)
	//绑定querystring
	r.GET("/loginForm", querystringHandler)
	// 启动webserver
	r.Run(":9000")
}
